import React from 'react'
import {connect} from 'react-redux'
import config from "config";
import { Button, message } from 'antd';
import SearchArea from 'components/search-area';
import menuRoute from "routes/menuRoute";
import SlideFrame from 'components/slide-frame';
import {deepFullCopy, messages} from "share/common";
import { setBusinessInterface } from "actions/financial-account";
import InterFaceRule from 'containers/financial-account/interface-definition/interface-rule';
import interfaceService from 'containers/financial-account/interface-definition/interface-service';
import baseService from "share/base.service";
import ResizeTable from 'components/resize-table'

class interfaceDefinition extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      searchForm: [
        {
          type: 'select',
          id: 'setOfBooksId',
          label: messages('financial-account.key93')/*账套*/,
          options: [],
          method: 'get',
          valueKey: 'id',
          labelKey: 'setOfBooksName',
          getParams: {roleType: 'TENANT'},
          getUrl: `${config.baseUrl}/api/setOfBooks/by/tenant`,
          disabled: !this.props.tenantMode,
          defaultValue: {
            label: props.company.setOfBooksName,
            key: props.company.setOfBooksId
          },
          event: 'setOfBooks',
          allowClear: false
        },{
          type: 'input',
          id: 'functionCodeORName',
          label: messages('financial-account.key143')/*业务接口编码/名称*/
        }
      ],
      searchParams: {
        setOfBooksId: this.props.company.setOfBooksId,
        setOfBooksIdOption: [{label: this.props.company.setOfBooksName, value: this.props.company.setOfBooksId}]
      },
      columns: [
        {title: messages('financial-account.key93')/*账套*/,dataIndex: 'setOfBooksName'},
        {title: messages('financial-account.key94')/*业务接口编码*/,dataIndex: 'functionCode'},
        {title: messages('financial-account.key95')/*业务接口名称*/,dataIndex: 'functionName'},
        {title: messages('financial-account.key5')/*是否预置*/,dataIndex: 'isDefault', width: 96, render:(value) => value ? messages('common.yes')/*是*/ : messages('common.no')/*否*/},
        {title: messages('common.column.status')/*状态*/,dataIndex: 'isEnable', width: 80, render:(value) => value ? messages('common.valid')/*生效*/ : messages('financial-account.key6')/*不生效*/},
        {title: messages('common.operation')/*操作*/,dataIndex: 'operation', render: (value,record) => {
            return <span>
              {
                !record.isDefault && (
                  <span>
                    <a onClick={e => this.handleEdit(e,record)}>{messages('common.edit')/*编辑*/}</a>
                    <span className="ant-divider"/>
                  </span>
                )
              }
              <a onClick={e => this.handleGoDetail(e,record)}>{messages('financial-account.key96')/*详情设置*/}</a>
            </span>;}}
      ],
      data: [],
      loading: false,
      pagination: {
        total: 0
      },
      page: 0,
      showSlideFrame: false,
      title: '',
      editRecord: {},
      hasInit: false,
      initLoading: false,
      interfaceDefinitionDetail: menuRoute.getRouteItem('interface-definition-detail')
    };
  }

  componentWillMount(){
    this.props.dispatch(setBusinessInterface({}));
    this.getList();
  }

  getList = () => {
    const { searchParams, page } = this.state;
    let temp = {};
    temp = deepFullCopy(searchParams);
    Object.keys(temp).map(item => {
      !temp[item] && delete temp[item];
    });
    delete temp.setOfBooksIdOption;
    temp.page = page;
    this.setState({loading: true});
    Promise.all([
      interfaceService.judgeInit(temp.setOfBooksId),
      interfaceService.getInterfaceList(temp)
    ]).then(res => {
      this.setState({
        loading: false,
        data: res[1].data.rows,
        pagination: {
          total: Number(res[1].data.total),
          current: page + 1,
          onChange: this.onChangePager,
        },
        hasInit: !res[0].data
      });
    }).catch(() => {
      message.error(messages('financial-account.key15')/*系统异常*/);
      this.setState({loading: false});
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  search = (result) => {
    const { searchParams } = this.state;
    searchParams.setOfBooksIdOption = result.setOfBooksIdOption;
    searchParams.setOfBooksId = result.setOfBooksId;
    searchParams.functionCodeORName = result.functionCodeORName;
    this.setState({searchParams, page: 0},() => {
      this.getList();
    })
  };

  clear = () => {
    this.setState({
      searchParams: {
        setOfBooksId: this.props.company.setOfBooksId,
        setOfBooksIdOption: [{
          label: this.props.company.setOfBooksName,
          value: this.props.company.setOfBooksId
        }]
      }
    }, () => {
      this.getList();
    })
  };

  handleNew = () => {
    this.setState({
      title: messages('financial-account.key57')/*新建业务接口定义*/,
      editRecord: {}
    },() => {
      this.setState({showSlideFrame: true});
    })
  };

  handleEdit = (e,record) => {
    e.stopPropagation();
    this.setState({
      title: messages('financial-account.key56')/*编辑业务接口定义*/,
      editRecord: record
    },() => {
      this.setState({showSlideFrame: true});
    })
  };

  handleGoDetail = (e,record) => {
    e.stopPropagation();
    this.props.dispatch(setBusinessInterface(record));
    this.context.router.push(this.state.interfaceDefinitionDetail.url);
  };

  handleReply = () => {
    const { searchParams } = this.state;
    const { user, tenant } = this.props;
    let params = {
      operatorOid: user.userOID,
      tenantId: tenant.id,
      setOfBooksId: searchParams.setOfBooksIdOption[0].value,
      setOfBooksName: searchParams.setOfBooksIdOption[0].label
    };
    this.setState({initLoading: true});
    interfaceService.initAll(params).then(() => {
      this.setState({initLoading: false},() => {
        this.getList();
      });
    }).catch(e => {
      this.setState({initLoading: false});
      message.error(e.response.data.message);
    })
  };

  isRefresh = (isRefresh) => {
    this.setState({showSlideFrame: false});
    isRefresh === true && this.getList();
  };

  searchEventHandle = (event, value) => {
    switch (event){
      case 'setOfBooks':
        this.formRef.setValues({
          functionCodeORName: ''
        });
        let temp = {};
        baseService.getSetOfBooksByTenant().then(res => {
          res.data.map(item => {
            if(item.id === value){
              temp.setOfBooksIdOption = [{label: item.setOfBooksName, value: item.id}];
              temp.setOfBooksId = value;
              this.setState({searchParams: temp, page: 0},() => {
                this.getList();
              });
            }
          })
        }).catch((e) => {
          message.error(e.response.data.message);
        });
        break;
      default:
        break;
    }
  };

  render(){
    const { searchForm, columns, data, loading, pagination, showSlideFrame, title, editRecord, hasInit, initLoading } = this.state;
    return (
      <div>
        <SearchArea searchForm={searchForm}
                    submitHandle={this.search}
                    isReturnLabel
                    wrappedComponentRef={inst => this.formRef = inst}
                    eventHandle={this.searchEventHandle}
                    clearHandle={this.clear}/>
        <div style={{margin:'10px 0px'}}>
          <Button type="primary" onClick={this.handleNew} disabled>{messages('common.create')}</Button>
          { hasInit && <Button type="primary" onClick={this.handleReply} style={{marginLeft:'10px'}} loading={initLoading}>{messages('financial-account.key97')/*初始化*/}</Button> }
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          loading={loading}
          rowKey={'id'}
          pagination={pagination}
          bordered/>
        <SlideFrame show={showSlideFrame}
                    title={title}
                    params={{
                      showSlideFrame,
                      editRecord
                    }}
                    content={InterFaceRule}
                    onClose={(isRefresh) => this.isRefresh(isRefresh)}
                    afterClose={(isRefresh) => this.isRefresh(isRefresh)}/>
      </div>
    )
  }
}

function mapStateToProps(state)  {
  return {
    tenantMode: state.main.tenantMode,
    company: state.login.company,
    user: state.login.user,
    tenant: state.login.tenant
  }
}

interfaceDefinition.contextTypes = {
  router: React.PropTypes.object
};

export default connect(mapStateToProps)(interfaceDefinition);
